import { useState, useEffect } from 'react'
import useGetUserInfo from './useGetUserInfo'
import { api_getUserInfo } from '@/api'
import { useRequest } from 'ahooks'
import { useDispatch } from 'react-redux'
import { loginReducer } from '@/store/modules/userReducer'

const useLoadUserData = () => {
  const dispatch = useDispatch()

  const [waitingData, setWaitingData] = useState(true)

  const { username } = useGetUserInfo()

  const { run } = useRequest(api_getUserInfo, {
    manual: true,
    onSuccess: result => {
      const { username, nickname } = result
      dispatch(loginReducer({ username, nickname }))
    },
    onFinally: () => {
      setWaitingData(false)
    },
  })

  useEffect(() => {
    if (username) {
      setWaitingData(false)
      return
    }
    run()
  }, [username])

  return { waitingData }
}

export default useLoadUserData
